package com.hl.card.modular.packBack.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.hl.card.common.controller.BaseController;
import com.hl.card.common.persistence.model.DisProfiParam;
import com.hl.card.common.persistence.model.Goods;
import com.hl.card.common.persistence.model.SalesDivision;
import com.hl.card.common.util.DateUtils;
import com.hl.card.common.util.PageData;
import com.hl.card.common.util.ResponseData;
import com.hl.card.core.log.LogObjectHolder;
import com.hl.card.core.support.BeanKit;
import com.hl.card.modular.packBack.service.CardService;
import com.hl.card.modular.packBack.service.GoodsSevice;
import com.hl.card.modular.packBack.service.ISalesDivisionService;
import com.hl.card.modular.packBack.service.StatisticsManagerService;
/**
 * 公卡管理
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/card")
public class CardContoller extends BaseController{
	
	private static final Logger logger = LoggerFactory.getLogger(CardContoller.class);
     	
	@Autowired
	private CardService cardService;

	private String PREFIX = "/dist/card/";
	
	/**
	 * 跳转卡包公卡信息列表
	 * @return
	 */
    @RequestMapping("/card_select_kb")
    public String indexKB(){
        return PREFIX+"card_select_kb.html";
    }
    
    /**
	 * 跳转比比购公卡信息列表
	 * @return
	 */
    @RequestMapping("/card_select_bbg")
    public String indexBBG(){
        return PREFIX+"card_select_bbg.html";
    }

	/**
	 * 跳转比比购公卡信息列表
	 * @return
	 */
	@RequestMapping("/card_select")
	public String indexBBGeth(){
		return PREFIX+"card_select.html";
	}

	/**
	 * 跳转比比购公卡(异步分账)信息列表
	 * @return
	 */
	@RequestMapping("/card_select_bbgansy")
	public String indexBBGANSY(){
		return PREFIX+"card_select_bbgansy.html";
	}

    /**
	 * 跳转深圳航旅公卡信息列表
	 * @return
	 */
    @RequestMapping("/card_select_szhl")
    public String indexSZHL(){
        return PREFIX+"card_select_szhl.html";
    }
    
    /**
	 * 跳转卡包公卡流水明细
	 * @return
	 */
    @RequestMapping("/companyCardFlow_bbgansy")
    public String indexFlowany(){
        return PREFIX+"companyCardFlow/companyCardFlow_bbgansy.html";
    }
    
    /**
	 * 
	 * @return
	 */
    @RequestMapping("/companyCardFlow_kb")
    public String indexFlowKB(){
        return PREFIX+"companyCardFlow/companyCardFlow_kb.html";
    }
    
    /**
	 * 跳转比比购公卡流水明细
	 * @return
	 */
    @RequestMapping("/companyCardFlow_bbg")
    public String indexFlowBBG(){
        return PREFIX+"companyCardFlow/companyCardFlow_bbg.html";
    }

    /**
	 * 跳转深圳航旅公卡流水明细
	 * @return
	 */
    @RequestMapping("/companyCardFlow_szhl")
    public String indexFlowSHZL(){
        return PREFIX+"companyCardFlow/companyCardFlow_szhl.html";
    }
    
    
    
    /**
	 * 跳转通证流水明细
	 * @return
	 */
    @RequestMapping("/companyCardFlow")
    public String indexFlow(){
        return PREFIX+"companyCardFlow/companyCardFlow.html";
    }

    /**
     * 跳转到公卡添加
     */
    @RequestMapping("/card_add")
    public String disProfiParamAdd(Model model) {
    	try {
    		logger.info(cardService.selectCardData(null).toString());
			model.addAttribute("cardTypes", cardService.selectCardData(null));
    	} catch (Exception e) {
			e.printStackTrace();
		}
    	return PREFIX + "card_add.html";
    }
 
    /**
     * 获取公卡信息列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public List<JSONObject> list(HttpServletRequest request) {
    	List<JSONObject> list = null;
    	try {
    		PageData pd = new PageData(request);
			list = cardService.selectCard(pd);
			logger.info("/card/list 获取数据：" + list.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return list;
    }
    
    /**
     * 新增公卡
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(HttpServletRequest request) {
    	try {
    		PageData pd = new PageData(request);
    		logger.info("/card/add 获取数据：" + pd.toString());
			int result = cardService.insertCard(pd);
			logger.info("成功添加公卡，更新数量:" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return super.SUCCESS_TIP;
    }
    
    /**
     * 删除公卡
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(HttpServletRequest request) {
    	try {
    		PageData pd = new PageData(request);
    		logger.info("/card/delete 获取数据：" + pd.toString());
    		int result = cardService.deleteCard(pd);
    		logger.info("成功删除公卡，更新数量:" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return super.SUCCESS_TIP;
    }
    
    /**
     * 获取公卡流水明细
     */
    @RequestMapping(value = "/flowList")
    @ResponseBody
    public List<JSONObject> flowList(HttpServletRequest request) {
    	List<JSONObject> list = null;
    	try {
    		PageData pd = new PageData(request);
    		if(
    			StringUtils.isBlank(pd.getString("merchantOrderNumber")) &&
    			StringUtils.isBlank(pd.getString("scoreFlowNumber")) &&
    			StringUtils.isBlank(pd.getString("oneselfAccount")) &&
    			StringUtils.isBlank(pd.getString("scoreFlowDirection")) &&
    			StringUtils.isBlank(pd.getString("oneselfCardNumber")) &&
				StringUtils.isBlank(pd.getString("userName")) &&
				StringUtils.isBlank(pd.getString("cardName")) &&
    			StringUtils.isBlank(pd.getString("cardType")) &&
    			StringUtils.isBlank(pd.getString("flowType")) &&
    			StringUtils.isBlank(pd.getString("createTime")) &&
    			StringUtils.isBlank(pd.getString("endTime"))
    		  ){
    			pd.put("sevenDays", "sevenDays");
    			logger.info("首次加载没有参数值，只需查询最近七天数据!");
    		}
			list = cardService.selectFlowList(pd);
			if(list.size() <= 0){
			}else{
				List<JSONObject> userList = cardService.selectUser(list);
				if(userList.size() <= 0){
				}else{
					for (int i = 0; i < list.size(); i++) {
						for (int j = 0; j < userList.size(); j++) {
							if(list.get(i).getString("ONESELF_ACCOUNT").equals(userList.get(j).getString("user_id"))){
								list.get(i).put("ONESELF_ACCOUNT", userList.get(j).getString("phone"));
							}
						}
					}
				}
			}
			//logger.info(userList.toString());
			//logger.info("/card/flowList 获取数据：" + list.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return list;
    }
    
    /**
     * 获取公卡流水明细
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public String export(HttpServletRequest request,HttpServletResponse response) {
    	logger.info("开始导出....aaa");
    	List<JSONObject> list = null;
    	try {
    		PageData pd = new PageData(request);
    		list = cardService.selectFlowList(pd);
			logger.info(list.toString());
			// 第一步，创建一个webbook，对应一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
			
			// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet    
	        HSSFSheet sheet = wb.createSheet("流水明细");
	        
	        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short    
	        HSSFRow row = sheet.createRow(0);
	        
	        // 第四步，创建单元格，并设置值表头 设置表头居中    
	        HSSFCellStyle style = wb.createCellStyle(); 
	        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
	        
	        HSSFCell cell = null;
	        
	        cell = row.createCell(1);
			cell.setCellValue("商户订单编号");
			cell.setCellStyle(style);
			
			cell = row.createCell(2);
			cell.setCellValue("账务流水号");
			cell.setCellStyle(style);
			
			cell = row.createCell(3);
			cell.setCellValue("绑定手机");
			cell.setCellStyle(style);
			
			cell = row.createCell(4);
			cell.setCellValue("卡号");
			cell.setCellStyle(style);
			
			cell = row.createCell(5);
			cell.setCellValue("卡片名称");
			cell.setCellStyle(style);
			
			cell = row.createCell(6);
			cell.setCellValue("收支流向");
			cell.setCellStyle(style);
			
			cell = row.createCell(7);
			cell.setCellValue("收支类型");
			cell.setCellStyle(style);
			
			cell = row.createCell(8);
			cell.setCellValue("收支名称");
			cell.setCellStyle(style);
			
			cell = row.createCell(9);
			cell.setCellValue("交易数量");
			cell.setCellStyle(style);
			
			cell = row.createCell(10);
			cell.setCellValue("交易后余额");
			cell.setCellStyle(style);
			
			cell = row.createCell(11);
			cell.setCellValue("生成时间");
			cell.setCellStyle(style);
	        
	        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，    
	        for (int i = 0; i < list.size(); i++) {
				row = sheet.createRow(i+1);
				cell = row.createCell(1);
				cell.setCellValue(list.get(i).getString("MERCHANT_ORDER_NUMBER"));
				cell.setCellStyle(style);
				
				cell = row.createCell(2);
				cell.setCellValue(list.get(i).getString("SCORE_FLOW_NUMBER"));
				cell.setCellStyle(style);
				
				cell = row.createCell(3);
				cell.setCellValue(list.get(i).getString("ONESELF_ACCOUNT"));
				cell.setCellStyle(style);
				
				cell = row.createCell(4);
				cell.setCellValue(list.get(i).getString("ONESELF_CARD_NUMBER"));
				cell.setCellStyle(style);
				
				cell = row.createCell(5);
				cell.setCellValue(list.get(i).getString("CARD_TYPE"));
				cell.setCellStyle(style);
				
				cell = row.createCell(6);
				cell.setCellValue(list.get(i).getString("SCORE_FLOW_DIRECTION"));
				cell.setCellStyle(style);
				
				cell = row.createCell(7);
				cell.setCellValue(list.get(i).getString("FLOW_TYPE"));
				cell.setCellStyle(style);
				
				cell = row.createCell(8);
				cell.setCellValue(list.get(i).getString("COMMENT"));
				cell.setCellStyle(style);
				
				cell = row.createCell(9);
				cell.setCellValue(list.get(i).getString("CURRENT_DEAL_SCORE"));
				cell.setCellStyle(style);
				
				cell = row.createCell(10);
				cell.setCellValue(list.get(i).getString("REMAIN_SCORE"));
				cell.setCellStyle(style);
				
				cell = row.createCell(11);
				cell.setCellValue(list.get(i).getString("CREATE_TIME"));
				cell.setCellStyle(style);
			}   
	        
	        /*// 第六步，将文件存到指定位置    
	        try    
	        {    
	            FileOutputStream fout = new FileOutputStream("C:/Users/Administrator/Desktop/导出结果.xls");    
	            wb.write(fout);    
	            fout.close();    
	        }    
	        catch (Exception e)    
	        {    
	            e.printStackTrace();    
	        }  */
	        
	        // 第六步，下载  
	        OutputStream out = null;    
	        try {        
	            out = response.getOutputStream();    
	            String fileName = "流水明细"+".xls";// 文件名    
	            response.setContentType("application/x-msdownload");    
	            response.setHeader("Content-Disposition", "attachment; filename="    
	                                                    + URLEncoder.encode(fileName, "UTF-8"));    
	            wb.write(out);    
	        } catch (Exception e) {    
	            e.printStackTrace();    
	        } finally {      
	            try {       
	                out.close();      
	            } catch (IOException e) {      
	                e.printStackTrace();    
	            }      
	        } 
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return "success";
    }
    
    

	
}
